import { formContextKey } from 'element-plus';
import { createRouter, createWebHashHistory, createWebHistory, } from 'vue-router'
import menuApi from "@/api/system/menu.js"
import Layout from '@/Layout/index.vue'
import component from 'element-plus/es/components/tree-select/src/tree-select-option.mjs';
import CookiesHelper from '@/util/logintoken';
import useUserStore from '@/store/app/user.js'

const routes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/Login.vue'),
        meta: {
            title: '登录',
            icon: '',
            show: false
        }
    },
    {
        path: "/:pathMatch(.*)*",
        component: () => import('@/views/error/404.vue'),
        meta: {
            title: '404',
            icon: '',
            show: false
        }
    },
    {
        path: '/401',
        component: () => import('@/views/error/401.vue'),
        meta: {
            title: '401',
            icon: '',
            show: false
        }
    },
    {
        path: '',
        component: () => import('@/Layout/index.vue'),
        redirect: '/index',
        meta: {
            title: '主页',
        },
        children: [
            {
                path: '/index',
                component: () => import('@/views/person/index.vue'),
                name: '/index',
                meta: {
                    title: '主页',
                    icon: '',
                    show: true
                }
            }
        ]
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

const loadDynamicRoutes = async () => {
    await menuApi.getTreeMenu({}).then(res => {
        //register routes
        var dyroutes = generateRoutes(res.data.data);
        dyroutes.forEach(item => router.addRoute(item));
    });
}


const generateRoutes = (menuList) => {
    let eroutes = [];
    let eroute = {};
    menuList.forEach((menu) => {
        if (menu.menuType == 1) {
            eroute = {
                name: menu.routeName,
                path: `/${menu.routeName}`,
                component: Layout,
                meta:{
                    title:menu.name,
                }
            };

            if (menu.children && menu.children.length > 0) {
                eroute.children = generateRoutes(menu.children);
            }

        }
        else if (menu.menuType == 2) {
            eroute = {
                name: menu.routeName,
                path: `/${menu.routeName}`,
                component: () => import(/* @vite-ignore */`/src/${menu.targetRoute}`),
                meta:{
                    title:menu.name,
                }
            };
        }
        eroutes.push(eroute);
    });
    return eroutes;
}


router.beforeEach(async (to, from, next) => {
    
    const loginToken = CookiesHelper.getLoginToken();
    
    //因为做的是后台管理模板，所以除了Login都需要进行登录操作；

    if (!loginToken && to.name != "login") {
        next({ name: "login" });
    }
    else {
        //动态加载路由
        if (!router.hasRoute(to.name)) {
            await loadDynamicRoutes();
            next(to.fullPath);
        }
        else {
            next();
        }
    }
});


export default router;